import sys
import json
from functools import wraps
from PyQt5.QtWidgets import (
    QApplication, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout, QMessageBox,
    QStackedWidget, QHBoxLayout, QTableWidget, QTableWidgetItem,
    QDialog, QFormLayout, QGroupBox, QListWidget, QTextEdit, QCheckBox,
    QComboBox, QSlider, QSpinBox, QGridLayout
)
from PyQt5.QtCore import Qt
from wallet import deposit, withdraw
from utils import (
    check_login, register_user, get_user_info, update_password,
    get_on_sale_equipments, get_my_orders, get_my_equipments,
    get_wallet_info, get_wallet_records,
    get_price_change_messages, mark_message_read
)
from cart import get_cart_items, add_to_cart, remove_from_cart, checkout_selected_items
from search import (
    search_equipments, filter_equipments,
    get_equipment_categories, get_equipment_rarities, get_equipment_level_range
)
from equip import (
    add_equipment, get_equipment_details, update_equipment, 
    remove_equipment, validate_equipment_data, format_equipment_details,
    reactivate_equipment
)

# 通用函数 - 表格操作
def setup_table(table, headers, data, selection_mode=QTableWidget.SingleSelection):
    """通用表格设置函数"""
    table.setSelectionBehavior(QTableWidget.SelectRows)
    table.setEditTriggers(QTableWidget.NoEditTriggers)
    table.setSelectionMode(selection_mode)
    table.setColumnCount(len(headers))
    table.setHorizontalHeaderLabels(headers)
    table.setRowCount(len(data))
    
    for row, row_data in enumerate(data):
        for col, val in enumerate(row_data):
            table.setItem(row, col, QTableWidgetItem(str(val)))
    
    table.resizeColumnsToContents()
    return table

# 基础对话框类
class BaseDialog(QDialog):
    def __init__(self, title, parent=None):
        super().__init__(parent)
        self.setWindowTitle(title)
        self.main_layout = QVBoxLayout(self)
        
    def add_form(self, form_items):
        """添加表单布局"""
        form = QFormLayout()
        for label, widget in form_items:
            form.addRow(label, widget)
        self.main_layout.addLayout(form)
        return form
        
    def add_buttons(self, buttons=None):
        """添加按钮布局"""
        if buttons is None:
            buttons = [("确定", self.accept), ("取消", self.reject)]
            
        btn_layout = QHBoxLayout()
        for text, callback in buttons:
            btn = QPushButton(text)
            btn.clicked.connect(callback)
            btn_layout.addWidget(btn)
        
        self.main_layout.addLayout(btn_layout)
        return btn_layout

class EquipmentDialog(BaseDialog):
    def __init__(self, categories, rarities, equipment_data=None, parent=None):
        super().__init__("编辑装备" if equipment_data else "发布新装备", parent)
        self.equipment_data = equipment_data
        self.is_edit = equipment_data is not None
        self.setMinimumWidth(400)
        
        # 装备名称
        self.name_input = QLineEdit()
        if self.is_edit:
            self.name_input.setText(str(equipment_data.get('EquipmentName', '')))
        
        # 类别
        self.category_combo = QComboBox()
        self.category_combo.addItems(categories)
        if self.is_edit and equipment_data.get('Category'):
            index = self.category_combo.findText(equipment_data['Category'])
            if index >= 0:
                self.category_combo.setCurrentIndex(index)
        
        # 等级
        self.level_spin = QSpinBox()
        self.level_spin.setRange(1, 999)
        if self.is_edit and equipment_data.get('Level'):
            self.level_spin.setValue(equipment_data['Level'])
        
        # 稀有度
        self.rarity_combo = QComboBox()
        self.rarity_combo.addItems([r for r in rarities if r != "全部"])
        if self.is_edit and equipment_data.get('Rarity'):
            index = self.rarity_combo.findText(equipment_data['Rarity'])
            if index >= 0:
                self.rarity_combo.setCurrentIndex(index)
        
        # 价格
        self.price_input = QLineEdit()
        if self.is_edit:
            self.price_input.setText(str(equipment_data.get('Price', '')))
            
        # 装备属性 - 攻击和防御数值
        self.attack_spin = QSpinBox()
        self.attack_spin.setRange(0, 9999)
        self.defense_spin = QSpinBox()
        self.defense_spin.setRange(0, 9999)
        
        # 如果是编辑模式，设置属性初始值
        if self.is_edit and equipment_data.get('Attributes'):
            attributes = equipment_data['Attributes']
            # 如果属性是字符串，尝试解析为字典
            if isinstance(attributes, str):
                try:
                    attributes = json.loads(attributes)
                except:
                    attributes = {}
                    
            self.attack_spin.setValue(attributes.get('攻击', 0))
            self.defense_spin.setValue(attributes.get('防御', 0))
        
        # 图片URL
        self.image_url_input = QLineEdit()
        if self.is_edit:
            self.image_url_input.setText(str(equipment_data.get('ImageURL', '')))
        
        # 添加表单
        form_items = [
            ("装备名称:", self.name_input),
            ("装备类别:", self.category_combo),
            ("装备等级:", self.level_spin),
            ("稀有度:", self.rarity_combo),
            ("价格:", self.price_input),
            ("攻击:", self.attack_spin),
            ("防御:", self.defense_spin),
            ("图片URL:", self.image_url_input)
        ]
        self.add_form(form_items)
        self.add_buttons()
    
    def get_equipment_data(self):
        """获取对话框中的装备数据"""
        data = {
            'name': self.name_input.text(),
            'category': self.category_combo.currentText(),
            'level': self.level_spin.value(),
            'rarity': self.rarity_combo.currentText(),
            'price': self.price_input.text(),
        }
        
        # 构建属性字典
        attributes = {
            "攻击": self.attack_spin.value(),
            "防御": self.defense_spin.value()
        }
        
        # 只有当至少有一个属性值大于0时才添加到数据中
        if attributes["攻击"] > 0 or attributes["防御"] > 0:
            data['attributes'] = attributes
        
        image_url = self.image_url_input.text().strip()
        if image_url:
            data['image_url'] = image_url
            
        return data

class EquipmentDetailsDialog(BaseDialog):
    def __init__(self, equipment_id, parent=None):
        super().__init__("装备详情", parent)
        self.setMinimumSize(400, 300)
        
        # 获取装备详情
        details = get_equipment_details(equipment_id)
        
        if details:
            # 使用format_equipment_details函数格式化显示
            details_text = format_equipment_details(details)
            info_text = QTextEdit()
            info_text.setReadOnly(True)
            info_text.setText(details_text)
            self.main_layout.addWidget(info_text)
        else:
            self.main_layout.addWidget(QLabel("无法获取装备详情"))
        
        # 关闭按钮
        close_btn = QPushButton("关闭")
        close_btn.clicked.connect(self.accept)
        self.main_layout.addWidget(close_btn, alignment=Qt.AlignRight)

class PasswordChangeDialog(BaseDialog):
    def __init__(self, parent=None):
        super().__init__("修改密码", parent)
        
        self.old_pwd = QLineEdit()
        self.old_pwd.setEchoMode(QLineEdit.Password)
        
        self.new_pwd = QLineEdit()
        self.new_pwd.setEchoMode(QLineEdit.Password)
        
        self.confirm_pwd = QLineEdit()
        self.confirm_pwd.setEchoMode(QLineEdit.Password)
        
        form_items = [
            ("当前密码:", self.old_pwd),
            ("新密码:", self.new_pwd),
            ("确认新密码:", self.confirm_pwd)
        ]
        
        self.add_form(form_items)
        self.add_buttons()

class DepositDialog(BaseDialog):
    def __init__(self, parent=None):
        super().__init__("充值", parent)
        
        self.amount_input = QLineEdit()
        self.amount_input.setPlaceholderText("请输入充值金额")
        
        form_items = [("充值金额：", self.amount_input)]
        self.add_form(form_items)
        self.add_buttons()

    def get_amount(self):
        try:
            return float(self.amount_input.text())
        except ValueError:
            return None

class WithdrawDialog(BaseDialog):
    def __init__(self, current_balance, parent=None):
        super().__init__("提现", parent)
        self.current_balance = current_balance
        
        self.amount_input = QLineEdit()
        self.amount_input.setPlaceholderText("请输入提现金额")
        
        form_items = [("提现金额：", self.amount_input)]
        self.add_form(form_items)
        
        self.balance_label = QLabel(f"当前余额：¥ {self.current_balance}")
        self.main_layout.addWidget(self.balance_label)
        self.add_buttons()

    def get_amount(self):
        try:
            return float(self.amount_input.text())
        except ValueError:
            return None

class PriceChangeMessagesDialog(BaseDialog):
    def __init__(self, user_id, parent=None):
        super().__init__("价格变动消息", parent)
        self.user_id = user_id
        self.setMinimumWidth(500)
        
        # 获取价格变动消息
        self.messages = get_price_change_messages(self.user_id)
        
        if not self.messages:
            self.main_layout.addWidget(QLabel("暂无价格变动消息"))
        else:
            for msg in self.messages:
                msg_box = QGroupBox()
                msg_layout = QVBoxLayout()
                
                # 构建消息内容
                equipment_info = QLabel(f"装备: {msg['EquipmentName']} (ID: {msg['EquipmentID']})")
                price_change = QLabel(f"价格变动: ¥{msg['OldPrice']} → ¥{msg['NewPrice']}")
                date_info = QLabel(f"变动时间: {msg['ChangeDate']}")
                
                # 设置未读消息为粗体
                if not msg['IsRead']:
                    font = equipment_info.font()
                    font.setBold(True)
                    equipment_info.setFont(font)
                    price_change.setFont(font)
                    
                msg_layout.addWidget(equipment_info)
                msg_layout.addWidget(price_change)
                msg_layout.addWidget(date_info)
                
                # 添加"标记为已读"按钮
                if not msg['IsRead']:
                    mark_read_btn = QPushButton("标记为已读")
                    mark_read_btn.clicked.connect(lambda checked, msg_id=msg['MessageID']: 
                                                 self.mark_as_read(msg_id))
                    msg_layout.addWidget(mark_read_btn)
                
                msg_box.setLayout(msg_layout)
                self.main_layout.addWidget(msg_box)
        
        close_btn = QPushButton("关闭")
        close_btn.clicked.connect(self.accept)
        self.main_layout.addWidget(close_btn)
    
    def mark_as_read(self, message_id):
        success = mark_message_read(message_id)
        if success:
            # 刷新对话框
            self.accept()
            new_dialog = PriceChangeMessagesDialog(self.user_id, self.parent())
            new_dialog.exec_()
        else:
            QMessageBox.warning(self, "错误", "标记已读失败")

class LoginWindow(QWidget):
    def __init__(self, stacked_widget):
        super().__init__()
        self.stacked_widget = stacked_widget
        self.setWindowTitle("登录")
        layout = QVBoxLayout()
        
        form_widgets = [
            ("用户名：", QLineEdit()),
            ("密码：", QLineEdit())
        ]
        
        self.user_input = form_widgets[0][1]
        self.pwd_input = form_widgets[1][1]
        self.pwd_input.setEchoMode(QLineEdit.Password)
        
        for label, widget in form_widgets:
            layout.addWidget(QLabel(label))
            layout.addWidget(widget)
        
        self.login_btn = QPushButton("登录")
        self.login_btn.clicked.connect(self.login)
        self.register_btn = QPushButton("注册新用户")
        self.register_btn.clicked.connect(self.show_register)
        
        layout.addWidget(self.login_btn)
        layout.addWidget(self.register_btn)
        self.setLayout(layout)

    def login(self):
        username = self.user_input.text()
        password = self.pwd_input.text()
        result = check_login(username, password)
        if result:
            user_id, role = result
            self.stacked_widget.user_id = user_id
            if role == "admin":
                self.stacked_widget.setCurrentIndex(1)
            elif role == "user":
                self.stacked_widget.setCurrentIndex(2)
            else:
                QMessageBox.warning(self, "登录失败", "未知用户角色")
        else:
            QMessageBox.warning(self, "登录失败", "用户名或密码错误")

    def show_register(self):
        self.stacked_widget.setCurrentIndex(3)

class RegisterWindow(QWidget):
    def __init__(self, stacked_widget):
        super().__init__()
        self.stacked_widget = stacked_widget
        self.setWindowTitle("注册新用户")
        layout = QVBoxLayout()
        
        form_widgets = [
            ("邮箱：", QLineEdit()),
            ("用户名：", QLineEdit()),
            ("密码：", QLineEdit())
        ]
        
        self.email_input = form_widgets[0][1]
        self.user_input = form_widgets[1][1]
        self.pwd_input = form_widgets[2][1]
        self.pwd_input.setEchoMode(QLineEdit.Password)
        
        for label, widget in form_widgets:
            layout.addWidget(QLabel(label))
            layout.addWidget(widget)
            
        self.register_btn = QPushButton("注册")
        self.register_btn.clicked.connect(self.register)
        self.back_btn = QPushButton("返回登录")
        self.back_btn.clicked.connect(self.back_to_login)
        
        layout.addWidget(self.register_btn)
        layout.addWidget(self.back_btn)
        self.setLayout(layout)

    def register(self):
        email = self.email_input.text()
        username = self.user_input.text()
        password = self.pwd_input.text()
        if not email or not username or not password:
            QMessageBox.warning(self, "注册失败", "请填写所有信息")
            return
        user_id = register_user(username, password, email)
        if user_id:
            QMessageBox.information(self, "注册成功", "注册成功，请登录")
            self.stacked_widget.setCurrentIndex(0)
        else:
            QMessageBox.warning(self, "注册失败", "用户名或邮箱已存在，或注册失败")

    def back_to_login(self):
        self.stacked_widget.setCurrentIndex(0)

class AdminMainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("管理员主界面")
        layout = QVBoxLayout()
        layout.addWidget(QLabel("欢迎，管理员！"))
        self.setLayout(layout)

NAV_ITEMS = [
    "个人中心",
    "正在出售的商品",
    "我的订单",
    "我发布的装备",
    "我的钱包",
    "购物车",
    "价格变动消息",
    "退出登录"
]

class UserMainWindow(QWidget):
    def __init__(self, stacked_widget):
        super().__init__()
        self.stacked_widget = stacked_widget
        self.setWindowTitle("用户主界面")
        main_layout = QHBoxLayout(self)
        self.nav_list = QListWidget()
        self.nav_list.addItems(NAV_ITEMS)
        self.nav_list.setFixedWidth(140)
        self.nav_list.setCurrentRow(0)
        self.nav_list.currentRowChanged.connect(self.switch_page)
        main_layout.addWidget(self.nav_list)
        self.pages = QStackedWidget()
        self.page_profile = self._build_profile_page()
        self.page_on_sale = self._build_on_sale_page()
        self.page_orders = self._build_orders_page()
        self.page_my_equip = self._build_my_equip_page()
        self.page_wallet = self._build_wallet_page()
        self.pages.addWidget(self.page_profile)
        self.pages.addWidget(self.page_on_sale)
        self.pages.addWidget(self.page_orders)
        self.pages.addWidget(self.page_my_equip)
        self.pages.addWidget(self.page_wallet)
        self.page_cart = self._build_cart_page()
        self.pages.addWidget(self.page_cart)
        main_layout.addWidget(self.pages)
        
        # 绑定装备管理按钮事件
        self.add_equip_btn.clicked.connect(self.show_add_equipment_dialog)
        self.edit_equip_btn.clicked.connect(self.show_edit_equipment_dialog)
        self.remove_equip_btn.clicked.connect(self.remove_selected_equipment)
        self.reactivate_equip_btn.clicked.connect(self.reactivate_selected_equipment)

    def switch_page(self, idx):
        if idx == 7:  # 退出登录
            self.stacked_widget.setCurrentIndex(0)
        elif idx == 6:  # 价格变动消息
            self.show_price_change_messages()
        else:
            self.pages.setCurrentIndex(idx)
            # 根据选择的页面刷新数据
            refresh_methods = [
                self.refresh_profile,
                self.refresh_on_sale,
                self.refresh_orders,
                self.refresh_my_equip,
                self.refresh_wallet,
                self.refresh_cart
            ]
            if 0 <= idx < len(refresh_methods):
                refresh_methods[idx]()

    def _build_profile_page(self):
        widget = QWidget()
        layout = QVBoxLayout(widget)
        group = QGroupBox("个人中心")
        form = QFormLayout()
        self.label_userid = QLabel()
        self.label_username = QLabel()
        self.label_email = QLabel()
        self.change_pwd_btn = QPushButton("修改密码")
        self.change_pwd_btn.clicked.connect(self.change_password)
        form.addRow("用户ID:", self.label_userid)
        form.addRow("用户名:", self.label_username)
        form.addRow("邮箱:", self.label_email)
        form.addRow("", self.change_pwd_btn)
        group.setLayout(form)
        layout.addWidget(group)
        layout.addStretch()
        return widget

    def _build_on_sale_page(self):
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 搜索框部分
        search_layout = QHBoxLayout()
        search_layout.addWidget(QLabel("搜索："))
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("输入装备ID或名称")
        self.search_btn = QPushButton("搜索")
        self.search_btn.clicked.connect(self.search_equipment)
        search_layout.addWidget(self.search_input)
        search_layout.addWidget(self.search_btn)
        search_layout.addStretch()
        
        # 筛选部分
        filter_group = QGroupBox("筛选选项")
        filter_group.setMaximumHeight(120)
        filter_layout = QGridLayout()
        filter_layout.setVerticalSpacing(10)
        filter_layout.setContentsMargins(10, 10, 10, 10)
        
        # 第一行: 装备类别和稀有度
        filter_layout.addWidget(QLabel("装备类别:"), 0, 0)
        self.category_combo = QComboBox()
        categories = get_equipment_categories()
        self.category_combo.addItems(categories)
        filter_layout.addWidget(self.category_combo, 0, 1)
        
        filter_layout.addWidget(QLabel("稀有度:"), 0, 2)
        self.rarity_combo = QComboBox()
        rarities = get_equipment_rarities()
        self.rarity_combo.addItems(rarities)
        filter_layout.addWidget(self.rarity_combo, 0, 3)
        
        # 第二行: 装备等级范围
        filter_layout.addWidget(QLabel("装备等级:"), 1, 0)
        level_widget = QWidget()
        level_layout = QHBoxLayout(level_widget)
        level_layout.setContentsMargins(0, 0, 0, 0)
        self.min_level_spin = QSpinBox()
        self.max_level_spin = QSpinBox()
        level_range = get_equipment_level_range()
        self.min_level_spin.setRange(level_range[0], level_range[1])
        self.max_level_spin.setRange(level_range[0], level_range[1])
        self.min_level_spin.setValue(level_range[0])
        self.max_level_spin.setValue(level_range[1])
        level_layout.addWidget(self.min_level_spin)
        level_layout.addWidget(QLabel("-"))
        level_layout.addWidget(self.max_level_spin)
        filter_layout.addWidget(level_widget, 1, 1)
        
        # 操作按钮
        btn_widget = QWidget()
        btn_layout = QHBoxLayout(btn_widget)
        btn_layout.setContentsMargins(0, 0, 0, 0)
        self.filter_btn = QPushButton("应用筛选")
        self.filter_btn.clicked.connect(self.apply_filter)
        self.reset_btn = QPushButton("重置筛选")
        self.reset_btn.clicked.connect(self.reset_filter)
        btn_layout.addWidget(self.filter_btn)
        btn_layout.addWidget(self.reset_btn)
        filter_layout.addWidget(btn_widget, 1, 3)
        
        filter_group.setLayout(filter_layout)
        
        # 装备表格
        self.table_on_sale = QTableWidget()
        
        # 操作按钮
        action_layout = QHBoxLayout()
        self.add_to_cart_btn = QPushButton("加入购物车")
        self.add_to_cart_btn.clicked.connect(self.add_selected_to_cart)
        action_layout.addWidget(self.add_to_cart_btn)
        action_layout.addStretch()
        
        # 组装页面
        layout.addLayout(search_layout)
        layout.addWidget(filter_group)
        layout.addWidget(self.table_on_sale)
        layout.addLayout(action_layout)
        
        return widget

    def _build_orders_page(self):
        widget = QWidget()
        layout = QVBoxLayout(widget)
        self.table_orders = QTableWidget()
        layout.addWidget(QLabel("我的订单"))
        layout.addWidget(self.table_orders)
        return widget

    def _build_my_equip_page(self):
        widget = QWidget()
        layout = QVBoxLayout(widget)
        self.table_my_equip = QTableWidget()
        btn_layout = QHBoxLayout()
        self.add_equip_btn = QPushButton("发布新装备")
        self.edit_equip_btn = QPushButton("编辑选中装备")
        self.remove_equip_btn = QPushButton("下架选中装备")
        self.reactivate_equip_btn = QPushButton("重新上架")  # 新增按钮
        btn_layout.addWidget(self.add_equip_btn)
        btn_layout.addWidget(self.edit_equip_btn)
        btn_layout.addWidget(self.remove_equip_btn)
        btn_layout.addWidget(self.reactivate_equip_btn)  # 添加到布局
        btn_layout.addStretch()
        layout.addWidget(QLabel("我发布的装备"))
        layout.addWidget(self.table_my_equip)
        layout.addLayout(btn_layout)
        return widget

    def _build_wallet_page(self):
        widget = QWidget()
        layout = QVBoxLayout(widget)
        balance_group = QGroupBox("账户余额")
        balance_layout = QVBoxLayout()
        self.label_balance = QLabel("0.00")
        self.label_balance.setStyleSheet("font-size: 20px; color: #2ecc71;")
        balance_layout.addWidget(self.label_balance)
        balance_group.setLayout(balance_layout)
        
        btn_layout = QHBoxLayout()
        self.deposit_btn = QPushButton("充值")
        self.withdraw_btn = QPushButton("提现")
        btn_layout.addWidget(self.deposit_btn)
        btn_layout.addWidget(self.withdraw_btn)
        btn_layout.addStretch()
        
        self.table_wallet = QTableWidget()
        layout.addWidget(balance_group)
        layout.addLayout(btn_layout)
        layout.addWidget(QLabel("交易记录:"))
        layout.addWidget(self.table_wallet)
        
        # 绑定充值和提现按钮
        self.deposit_btn.clicked.connect(self.show_deposit_dialog)
        self.withdraw_btn.clicked.connect(self.show_withdraw_dialog)
        return widget

    def _build_cart_page(self):
        widget = QWidget()
        layout = QVBoxLayout(widget)
        self.table_cart = QTableWidget()
        self.table_cart.setSelectionMode(QTableWidget.MultiSelection)
        
        # 添加全选功能
        select_layout = QHBoxLayout()
        self.select_all_cb = QCheckBox("全选")
        self.select_all_cb.clicked.connect(self.toggle_select_all)
        select_layout.addWidget(self.select_all_cb)
        select_layout.addStretch()
        
        btn_layout = QHBoxLayout()
        self.remove_cart_btn = QPushButton("移除选中装备")
        self.checkout_btn = QPushButton("结算选中装备")
        btn_layout.addWidget(self.remove_cart_btn)
        btn_layout.addWidget(self.checkout_btn)
        btn_layout.addStretch()
        
        layout.addWidget(QLabel("购物车"))
        layout.addLayout(select_layout)
        layout.addWidget(self.table_cart)
        layout.addLayout(btn_layout)
        
        self.remove_cart_btn.clicked.connect(self.remove_selected_from_cart)
        self.checkout_btn.clicked.connect(self.checkout_selected_items)
        return widget
    
    def search_equipment(self):
        """根据关键词搜索装备"""
        keyword = self.search_input.text().strip()
        if not keyword:
            self.refresh_on_sale()
            return
            
        data = search_equipments(keyword)
        self.update_equipment_table(data)
        if not data:
            QMessageBox.information(self, "搜索结果", "没有找到匹配的装备")
            
    def apply_filter(self):
        """应用筛选条件"""
        category = self.category_combo.currentText()
        if category == "全部":
            category = None
            
        min_level = self.min_level_spin.value()
        max_level = self.max_level_spin.value()
        
        if min_level > max_level:
            QMessageBox.warning(self, "筛选错误", "最低等级不能高于最高等级")
            return
            
        rarity = self.rarity_combo.currentText()
        if rarity == "全部":
            rarity = None
            
        search_text = self.search_input.text().strip() or None
        
        data = filter_equipments(category, min_level, max_level, rarity, search_text)
        self.update_equipment_table(data)
        
        if not data:
            QMessageBox.information(self, "筛选结果", "没有找到匹配的装备")
    
    def reset_filter(self):
        """重置所有筛选条件"""
        self.category_combo.setCurrentIndex(0)
        level_range = get_equipment_level_range()
        self.min_level_spin.setValue(level_range[0])
        self.max_level_spin.setValue(level_range[1])
        self.rarity_combo.setCurrentIndex(0)
        self.search_input.clear()
        self.refresh_on_sale()
    
    def update_equipment_table(self, data):
        """更新装备表格显示"""
        headers = ["装备ID", "装备名称", "类别", "等级", "稀有度", "价格", "上架时间", "状态"]
        setup_table(self.table_on_sale, headers, data)
    
    def toggle_select_all(self):
        checked = self.select_all_cb.isChecked()
        for row in range(self.table_cart.rowCount()):
            self.table_cart.setRangeSelected(
                QTableWidget.QTableWidgetSelectionRange(row, 0, row, self.table_cart.columnCount()-1),
                checked
            )
    
    # 统一的表格刷新方法
    def refresh_table(self, table, headers, data_func, *args):
        """通用表格刷新方法"""
        data = data_func(*args)
        setup_table(table, headers, data)

    def refresh_all(self):
        """刷新所有页面数据"""
        self.refresh_profile()
        self.refresh_on_sale()
        self.refresh_orders()
        self.refresh_my_equip()
        self.refresh_wallet()
        self.refresh_cart()

    def refresh_profile(self):
        """刷新个人信息"""
        user_id = self.stacked_widget.user_id
        info = get_user_info(user_id)
        if info:
            self.label_userid.setText(str(info[0]))
            self.label_username.setText(str(info[1]))
            self.label_email.setText(str(info[2]))

    def refresh_on_sale(self):
        """刷新出售中的装备"""
        data = get_on_sale_equipments()
        self.update_equipment_table(data)

    def refresh_orders(self):
        """刷新订单列表"""
        user_id = self.stacked_widget.user_id
        headers = ["交易ID", "装备ID", "卖家ID", "买家ID", "价格", "状态", "交易时间"]
        self.refresh_table(self.table_orders, headers, get_my_orders, user_id)

    def refresh_my_equip(self):
        """刷新我的装备列表"""
        user_id = self.stacked_widget.user_id
        headers = ["装备ID", "装备名称", "价格", "上架时间", "状态"]
        self.refresh_table(self.table_my_equip, headers, get_my_equipments, user_id)

    def refresh_wallet(self):
        """刷新钱包信息"""
        user_id = self.stacked_widget.user_id
        balance = get_wallet_info(user_id)
        self.label_balance.setText(f"¥ {balance}")
        
        headers = ["记录ID", "类型", "金额", "时间"]
        self.refresh_table(self.table_wallet, headers, get_wallet_records, user_id)

    def refresh_cart(self):
        """刷新购物车"""
        user_id = self.stacked_widget.user_id
        headers = ["装备ID", "装备名称", "价格", "卖家ID", "上架时间", "状态"]
        self.refresh_table(self.table_cart, headers, get_cart_items, user_id)
        # 重置全选复选框
        self.select_all_cb.setChecked(False)

    def change_password(self):
        """修改密码"""
        dialog = PasswordChangeDialog(self)
        if dialog.exec_():
            old_pwd = dialog.old_pwd.text()
            new_pwd = dialog.new_pwd.text()
            confirm_pwd = dialog.confirm_pwd.text()
            if not old_pwd or not new_pwd or not confirm_pwd:
                QMessageBox.warning(self, "修改失败", "请填写所有密码字段")
                return
            if new_pwd != confirm_pwd:
                QMessageBox.warning(self, "修改失败", "两次输入的新密码不一致")
                return
            user_id = self.stacked_widget.user_id
            if update_password(user_id, new_pwd):
                QMessageBox.information(self, "修改成功", "密码已成功修改")
            else:
                QMessageBox.warning(self, "修改失败", "密码修改失败，请重试")

    def show_deposit_dialog(self):
        """显示充值对话框"""
        dlg = DepositDialog(self)
        if dlg.exec_():
            amount = dlg.get_amount()
            if amount is None or amount <= 0:
                QMessageBox.warning(self, "充值失败", "请输入有效的充值金额")
                return
            user_id = self.stacked_widget.user_id
            success, msg = deposit(user_id, amount)
            if success:
                QMessageBox.information(self, "充值成功", msg)
                self.refresh_wallet()
            else:
                QMessageBox.warning(self, "充值失败", msg)
    
    def show_withdraw_dialog(self):
        """显示提现对话框"""
        balance = get_wallet_info(self.stacked_widget.user_id)
        dlg = WithdrawDialog(balance, self)
        if dlg.exec_():
            amount = dlg.get_amount()
            if amount is None or amount <= 0:
                QMessageBox.warning(self, "提现失败", "请输入有效的提现金额")
                return
            if amount > balance:
                QMessageBox.warning(self, "提现失败", "提现金额不能大于当前余额")
                return
            user_id = self.stacked_widget.user_id
            success, msg = withdraw(user_id, amount)
            if success:
                QMessageBox.information(self, "提现成功", msg)
                self.refresh_wallet()
            else:
                QMessageBox.warning(self, "提现失败", msg)
    
    def show_price_change_messages(self):
        """显示价格变动消息对话框"""
        dlg = PriceChangeMessagesDialog(self.stacked_widget.user_id, self)
        dlg.exec_()
    
    def add_selected_to_cart(self):
        """将选中装备添加到购物车"""
        selected = self.table_on_sale.currentRow()
        if selected < 0:
            QMessageBox.warning(self, "提示", "请先选择一个装备")
            return
            
        equipment_id = self.table_on_sale.item(selected, 0).text()
        user_id = self.stacked_widget.user_id
        success, msg = add_to_cart(user_id, equipment_id)
        if success:
            QMessageBox.information(self, "成功", "已加入购物车")
            self.refresh_cart()
        else:
            QMessageBox.warning(self, "失败", msg or "加入购物车失败")
    
    def remove_selected_from_cart(self):
        """从购物车中移除选中装备"""
        selected_rows = [index.row() for index in self.table_cart.selectedIndexes() if index.column() == 0]
        if not selected_rows:
            QMessageBox.warning(self, "提示", "请先选择要移除的装备")
            return
        
        # 去重，因为多列选择会导致重复的行
        selected_rows = list(set(selected_rows))
        user_id = self.stacked_widget.user_id
        
        # 逐个移除选中的装备
        success_count = 0
        fail_count = 0
        for row in selected_rows:
            equipment_id = self.table_cart.item(row, 0).text()
            success, msg = remove_from_cart(user_id, equipment_id)
            if success:
                success_count += 1
            else:
                fail_count += 1
        
        if success_count > 0:
            QMessageBox.information(self, "成功", f"已成功移除 {success_count} 件装备")
        if fail_count > 0:
            QMessageBox.warning(self, "失败", f"有 {fail_count} 件装备移除失败")
            
        self.refresh_cart()
    
    def checkout_selected_items(self):
        """结算选中的购物车项目"""
        selected_rows = [index.row() for index in self.table_cart.selectedIndexes() if index.column() == 0]
        if not selected_rows:
            QMessageBox.warning(self, "提示", "请先选择要结算的装备")
            return
        
        # 去重
        selected_rows = list(set(selected_rows))
        user_id = self.stacked_widget.user_id
        
        # 收集要结算的装备ID
        equipment_ids = [self.table_cart.item(row, 0).text() for row in selected_rows]
        
        success, msg = checkout_selected_items(user_id, equipment_ids)
        if success:
            QMessageBox.information(self, "结算成功", msg or f"成功结算了 {len(equipment_ids)} 件装备")
            self.refresh_cart()
            self.refresh_wallet()
            self.refresh_orders()
        else:
            QMessageBox.warning(self, "结算失败", msg or "购物车结算失败")
    
    # 装备管理通用方法
    def handle_equipment_action(self, equipment_id=None, action_type="add"):
        """通用装备操作处理方法"""
        categories = [c for c in get_equipment_categories() if c != "全部"]
        rarities = get_equipment_rarities()
        details = None
        
        if equipment_id:
            details = get_equipment_details(equipment_id)
            if not details:
                QMessageBox.warning(self, "错误", "无法获取装备详情")
                return
        
        dialog = EquipmentDialog(categories, rarities, details, parent=self)
        if not dialog.exec_():
            return
            
        data = dialog.get_equipment_data()
        valid, msg = validate_equipment_data(
            data['name'], data['category'], data['level'],
            data['rarity'], data['price']
        )
        
        if not valid:
            QMessageBox.warning(self, "数据无效", msg)
            return
            
        user_id = self.stacked_widget.user_id
        
        if action_type == "add":
            success, result = add_equipment(
                user_id, data['name'], data['category'], 
                data['level'], data['rarity'], data['price'],
                data.get('attributes'), data.get('image_url')
            )
            if success:
                QMessageBox.information(self, "成功", f"装备已发布，ID: {result}")
            else:
                QMessageBox.warning(self, "失败", f"发布装备失败: {result}")
        else:  # edit
            success, msg = update_equipment(
                equipment_id, user_id, 
                name=data['name'], 
                category=data['category'],
                level=data['level'],
                rarity=data['rarity'],
                price=data['price'],
                attributes=data.get('attributes'),
                image_url=data.get('image_url')
            )
            if success:
                QMessageBox.information(self, "成功", msg)
            else:
                QMessageBox.warning(self, "失败", msg)
                
        self.refresh_my_equip()
        
    def show_add_equipment_dialog(self):
        """显示添加装备对话框"""
        self.handle_equipment_action(action_type="add")

    def show_edit_equipment_dialog(self):
        """显示编辑装备对话框"""
        selected = self.table_my_equip.currentRow()
        if selected < 0:
            QMessageBox.warning(self, "提示", "请先选择一个装备")
            return
            
        equipment_id = self.table_my_equip.item(selected, 0).text()
        self.handle_equipment_action(equipment_id, action_type="edit")

    def remove_selected_equipment(self):
        """下架选中的装备"""
        selected = self.table_my_equip.currentRow()
        if selected < 0:
            QMessageBox.warning(self, "提示", "请先选择一个装备")
            return
            
        equipment_id = self.table_my_equip.item(selected, 0).text()
        equipment_name = self.table_my_equip.item(selected, 1).text()
        
        # 确认对话框
        reply = QMessageBox.question(
            self, "确认下架", 
            f"确定要下架装备 '{equipment_name}' (ID: {equipment_id}) 吗？",
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            user_id = self.stacked_widget.user_id
            success, msg = remove_equipment(equipment_id, user_id)
            
            if success:
                QMessageBox.information(self, "成功", msg)
                self.refresh_my_equip()
            else:
                QMessageBox.warning(self, "失败", msg)
    
    def reactivate_selected_equipment(self):
        """重新上架选中的装备"""
        selected = self.table_my_equip.currentRow()
        if selected < 0:
            QMessageBox.warning(self, "提示", "请先选择一个装备")
            return
            
        equipment_id = self.table_my_equip.item(selected, 0).text()
        equipment_name = self.table_my_equip.item(selected, 1).text()

        # 确认对话框
        reply = QMessageBox.question(
            self, "确认上架", 
            f"确定要重新上架装备 '{equipment_name}' (ID: {equipment_id}) 吗？",
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            user_id = self.stacked_widget.user_id
            success, msg = reactivate_equipment(equipment_id, user_id)
            
            if success:
                QMessageBox.information(self, "成功", msg)
                self.refresh_my_equip()
            else:
                QMessageBox.warning(self, "失败", msg)

class MyStackedWidget(QStackedWidget):
    def __init__(self):
        super().__init__()
        self.user_id = None
        self.login_win = LoginWindow(self)
        self.admin_win = AdminMainWindow()
        self.user_main_win = UserMainWindow(self)
        self.register_win = RegisterWindow(self)
        self.addWidget(self.login_win)      # index 0
        self.addWidget(self.admin_win)      # index 1
        self.addWidget(self.user_main_win)  # index 2
        self.addWidget(self.register_win)   # index 3

if __name__ == "__main__":
    app = QApplication(sys.argv)
    stacked_widget = MyStackedWidget()
    stacked_widget.setFixedSize(900, 600)
    stacked_widget.show()
    sys.exit(app.exec_())